<template>
  <span ref="iconRef" :class="[prefix, className, { 'reverse': mergedProps.reverse }]" :style="{ ...customStyle, ...animationStyle }" @click="handleClick">
    <template v-if="isSvgString">
      <div v-html="iconName"></div>
    </template>
    <template v-else-if="typeof iconName === 'string' && iconName.includes(':')">
      <Icon :icon="iconName" :size="typeof mergedProps.size === 'number' ? `${mergedProps.size}px` : mergedProps.size" :color="mergedProps.color" />
    </template>
    <template v-else>
      {{ iconName }}
    </template>
  </span>
</template>

<script setup lang="ts">
import { computed,  onMounted, ref } from 'vue';
import { Icon } from '@iconify/vue';
import { setupGlobalIcons } from './iconManager';
import { useAnimationStyle, animationPause, animationResume, animationStop, animationRestart } from '../../animation/animationManager';
import type { TuiIconProps, TuiIconWithNameProps } from './types';

// 定义emits
const emits = defineEmits([
  'click'
]);

// 使用withDefaults设置默认值
const props = withDefaults(defineProps<TuiIconProps>(), {
  size: '16px',
  className: '',
  style: () => ({}),
  customIcons: () => ({}),
  animation: 'none',
  animationDuration: undefined,
  animationIterationCount: true,
  animationDelay: 0,
  animationEnabled: true,
  reverse: false,
});

// 处理用户提供的自定义图标
onMounted(() => {
  // 如果有自定义图标，注册到全局
  if (props.customIcons && Object.keys(props.customIcons).length > 0) {
    setupGlobalIcons(props.customIcons);
  }
});

// 内部常量
const prefix = 'tui-icon';

// 引用图标元素
const iconRef = ref<HTMLElement | null>(null);



// 重启动画方法
const restartAnimation = () => {
  if (iconRef.value && getMergedProps.value.animationEnabled) {
    animationRestart(iconRef.value);
  }
};

// 暂停动画方法
const pauseAnimation = () => {
  if (iconRef.value) {
    animationPause(iconRef.value);
  }
};

// 恢复动画方法
const resumeAnimation = () => {
  if (iconRef.value && getMergedProps.value.animationEnabled) {
    animationResume(iconRef.value);
  }
};

// 停止动画方法
const stopAnimation = () => {
  if (iconRef.value) {
    animationStop(iconRef.value);
  }
};

// 合并属性的辅助函数
const getMergedProps = computed(() => {
  // 如果icon是TuiIconWithNameProps对象，需要合并属性
  if (typeof props.icon === 'object' && props.icon !== null && 'icon' in props.icon && typeof props.icon.icon === 'string') {
    const iconProps = props.icon as TuiIconWithNameProps;
    // 创建一个新对象，合并当前组件的props和iconProps
    // 当前组件的props优先级更高
    return {
      // 先展开基础属性，确保它们有值
      ...props,
      // 合并iconProps的属性，允许覆盖当前组件的props
      size: props.size !== undefined ? props.size : iconProps.size,
      color: props.color !== undefined ? props.color : iconProps.color,
      className: props.className !== undefined ? props.className : iconProps.className,
      style: props.style !== undefined ? props.style : iconProps.style,
      customIcons: props.customIcons !== undefined ? props.customIcons : iconProps.customIcons,
      animation: props.animation !== undefined && props.animation !== 'none' ? props.animation : (iconProps.animation || 'none'),
      animationDuration: props.animationDuration !== undefined ? props.animationDuration : iconProps.animationDuration,
      animationIterationCount: props.animationIterationCount !== undefined ? props.animationIterationCount : iconProps.animationIterationCount,
      animationDelay: props.animationDelay !== undefined ? props.animationDelay : iconProps.animationDelay,
      animationEnabled: props.animationEnabled !== undefined ? props.animationEnabled : iconProps.animationEnabled,
      // 确保icon是最终的字符串值
      icon: iconProps.icon
    };
  }

  return props;
});

// 计算自定义样式
const customStyle = computed(() => {
  const mergedProps = getMergedProps.value;
  const baseStyle: Record<string, string | number> = {};

  // 根据size属性设置宽高
  if (typeof mergedProps.size === 'number') {
    baseStyle.width = `${mergedProps.size}px`;
    baseStyle.height = `${mergedProps.size}px`;
  } else if (typeof mergedProps.size === 'string') {
    if (mergedProps.size.includes('px')) {
      baseStyle.width = mergedProps.size;
      baseStyle.height = mergedProps.size;
    } else {
      baseStyle.width = `${mergedProps.size}px`;
      baseStyle.height = `${mergedProps.size}px`;
    }
  }

  // 应用颜色样式
  if (mergedProps.color) {
    baseStyle.color = mergedProps.color;
    // 对于SVG，需要额外设置fill属性来继承颜色
    baseStyle['--tui-icon-color'] = mergedProps.color;
  }

  return { ...baseStyle, ...mergedProps.style };
});

// 计算动画样式
const animationStyle = computed(() => {
  const mergedProps = getMergedProps.value;

  if (!mergedProps.animationEnabled || mergedProps.animation === 'none') {
    return {};
  }
  // 设置CSS变量来控制动画迭代次数
  const style = useAnimationStyle(mergedProps.animation, {
    delay: mergedProps.animationDelay!,
    duration: mergedProps.animationDuration!,
    iterationCount: mergedProps.animationIterationCount!
  });

  // 初始状态默认为运行
  style['animation-play-state'] = 'running';

  return style;
});

// 暴露方法
defineExpose({
  stopAnimation,
  restartAnimation,
  pauseAnimation,
  resumeAnimation
});

// 计算合并后的属性，使其在模板中可用
const mergedProps = computed(() => getMergedProps.value);

// 检查是否为SVG字符串
const isSvgString = computed(() => {
  const name = iconName.value;
  return typeof name === 'string' && name.trim().startsWith('<svg');
});

// 解析图标名称，支持 tui-icon 前缀格式、TuiIconWithNameProps对象和SVG字符串
const iconName = computed(() => {
  let name = props.icon;

  // 处理 tui-icon 前缀格式
  if (typeof name === 'string') {
    if (name.startsWith('tui-icon ')) {
      return name.replace('tui-icon ', '');
    }
    return name;
  } else if (typeof name === 'object' && name !== null && 'icon' in name && typeof name.icon === 'string') {
    // 如果是TuiIconWithNameProps对象，获取其icon属性值
    return name.icon;
  }

  // 确保始终返回字符串类型，即使在异常情况下
  return '';
});

// 处理点击事件
const handleClick = (e: MouseEvent) => {
  emits('click', e);
};

</script>

<style scoped>
.tui-icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  position: relative;
  --tui-animation-duration: var(--tui-animation-duration, 1s);
  /* 确保与文字垂直对齐 */
  vertical-align: middle;
}

/* 确保SVG图标继承颜色和大小 */
.tui-icon svg {
  width: 100%;
  height: 100%;
  fill: currentColor !important;
  overflow: visible;
  display: block;
  max-width: 100%;
  max-height: 100%;
}

/* 动画类将通过JS动态生成 */

/* 反转颜色样式 - 方法一实现 */
.tui-icon.reverse {
  background-color: currentColor;
  color: #fff;
  border-radius: 2px;
  padding: 2px;
}

.tui-icon.reverse svg {
  filter: invert(100%);
}
</style>